<template>
	<view>
		<drag-button text="上传" color="#1E91E6" icon="/static/images/icon/upload.png" :margin="60" @btnClick="upload" />
	</view>
</template>

<script>
	import * as sqliteUtil from '@/utils/sqlite.js'
	import * as sqliteInspect from '@/utils/business/inspectSqlite.js'
	import { utilities, file, notice } from '@/utils/common.js'
	import { getTaskInfo, uploadTask, logCollectStatusBatch } from '@/api/business/inspect.js'
	import { uploadDefect } from '@/api/business/defect.js'
	import { accessToken } from '@/api/platform/oauth.js'
	import { getNetwork } from '@/utils/device.js'
	import project from '@/utils/config/project.js'
	
	export default {
		props: {
			taskId: {
				type: String,
				default: ""
			}
		},
		data() {
			return {
				
			}
		},
		methods: {
			async upload() {
				// 查询网络环境
				let netFlag = getNetwork()
				if(!netFlag) {
					notice.toast(this.$t('inspection.message.checkNetwork'))
					return
				}
				
				// 申请token
				const param = {
					client_id: project.OFFLINE_CLIENT_ID,
					client_secret: project.OFFLINE_CLIENT_SECRET,
					grant_type: project.OFFLINE_GRANT_TYPE,
					username: ""
				}
				let tokenData = await accessToken(param)
				let token = tokenData.data.access_token
				uni.setStorageSync("_app_token", token)
				
				// 查询任务状态
				let res = await getTaskInfo(this.taskId)
				if(res.data.taskState == '3' || res.data.taskState == '-1') {
					notice.toast(this.$t('inspection.message.taskCompleted'))
					return
				}
				
				uni.showLoading({
					title: this.$t('baseCommon.message.pleaseWait'),
					mask: true
				})
				
				// 巡检任务
				let taskList = await sqliteUtil.selectTableInfo('m_ri_task', 'task_id', this.taskId)
				utilities.formatHumpLineTransfer(taskList)
				// 巡检任务附件
				let taskFiles = await this.getFileList(taskList)
				
				// 检查项
				let inspectList = await sqliteUtil.selectTableInfo('m_ri_task_inspection', 'task_id', this.taskId)
				utilities.formatHumpLineTransfer(inspectList)
				// 检查项附件
				let inspectFiles = await this.getFileList(inspectList)
				
				// 检查项测点
				let inspMpList = await sqliteUtil.selectTableInfo('m_ri_task_insp_mp', 'task_id', this.taskId)
				utilities.formatHumpLineTransfer(inspMpList)
				
				// 异常情况
				let abnormalList = await sqliteUtil.selectTableInfo('m_ri_task_inspection_abnormal', 'task_id', this.taskId)
				utilities.formatHumpLineTransfer(abnormalList)
				
				// 缺陷
				let defectList = []
				for(let i=0; i<abnormalList.length; i++) {
					let item = abnormalList[i]
					if(item.dfNo) {
						await sqliteUtil.selectTableInfo('m_df_information', 'df_id', item.dfNo).then(res=>{
							utilities.formatHumpLineTransfer(res)
							defectList.push(res[0])
						})
					}
				}
				// 关联的缺陷附件
				let defectFiles = await this.getFileList(defectList)
				
				// 测量数据
				let mpDataList = []
				for(let i=0; i<inspMpList.length; i++) {
					let item = inspMpList[i]
					await sqliteInspect.getMpDataList(item.mpNo, taskList[0].actualStartTime, utilities.getNowDateTime()).then(res=>{
						if(res.length > 0) {
							utilities.formatHumpLineTransfer(res)
							// 长度超过300进行截取，防止接口报错
							res.forEach(item => {
								if(item.dataValue) {
									if(mpDataList.findIndex(r => r.mpDataId == item.mpDataId) === -1) {
										let dataValueArr = item.dataValue.split(",")
										if(dataValueArr.length > 300) {
											dataValueArr = dataValueArr.slice(dataValueArr.length - 257)
											item.dataValue = dataValueArr.join()
										}
										mpDataList.push(item)
									}
								} else {
									sqliteUtil.deleteTableInfo('m_eq_mp_data', 'mp_data_id', item.mpDataId)
								}
							})
						}
					})
				}
				
				// 缺陷处理
				let defectFlag = await this.handleUpload('defect', defectFiles, defectList)
				
				// 检查项处理
				let inspectFlag = await this.handleUpload('inspect', inspectFiles, inspectList)
				
				// 巡检任务处理
				let taskFlag = await this.handleUpload('task', taskFiles, taskList)
				
				if(!defectFlag || !inspectFlag || !taskFlag) {
					notice.toast(this.$t('inspection.offline.uploadFail'))
					return
				}
				
				// 调用上传接口（重新获取数据）
				// 巡检任务
				let newTaskList = await sqliteUtil.selectTableInfo('m_ri_task', 'task_id', this.taskId)
				utilities.formatHumpLineTransfer(newTaskList)
				
				// 检查项
				let newInspectList = await sqliteUtil.selectTableInfo('m_ri_task_inspection', 'task_id', this.taskId)
				utilities.formatHumpLineTransfer(newInspectList)
				
				// 补充信息
				let addList = await sqliteUtil.selectTableInfo('m_ri_task_info', 'task_id', this.taskId)
				utilities.formatHumpLineTransfer(addList)
				let addInfo = addList.length > 0 ? addList[0] : {}
				
				let taskInfo = newTaskList[0]
				taskInfo.taskInspectionList = newInspectList
				taskInfo.riTaskInspMpList = inspMpList
				taskInfo.riTaskInspAbnList = abnormalList
				
				let params = {
					riTaskIo: taskInfo,
					eqMpDataIoList: mpDataList,
					riTaskInfoIo: addInfo
				}
				
				let status = 0
				await uploadTask(params).then(res=>{
					if(res.data) {
						status = 1
						notice.toast(this.$t('inspection.offline.uploadSuccess'))
					} else {
						status = 2
						notice.toast(res.msg)
					}
				})
				
				// 业务操作日志
				this.$saveOpLog('offline_upload', 'offline_task', this.taskId)
				
				// 新增任务上传记录
				await sqliteInspect.createMRiTaskUpload()
				let logParams = {
					taskId: this.taskId,
					nodeId: 'inspect',
					nodeName: '巡检',
					seq: "",
					uploadState: status === 0 ? '0' : status === 1 ? '10' : '20',
					uploadTime: utilities.getNowDateTime(),
					createTime: utilities.getNowDateTime(),
					updateTime: utilities.getNowDateTime()
				}
				sqliteInspect.insertMRiTaskUpload(logParams)
				
				// 采集情况
				let collectList = await sqliteUtil.selectTableInfo('m_cpis_app_collect_status')
				utilities.formatHumpLineTransfer(collectList)
				logCollectStatusBatch(collectList)
				
				uni.hideLoading()
				
				// 上传成功并且状态为已完成删除本地数据
				if(status === 1 && taskInfo.taskState == '3') {
					this.deleteOfflineTask()
					uni.redirectTo({
						url: '/pages/business/inspect/offline/index'
					})
				}
			},
			// 获取附件
			async getFileList(dataList) {
				let fileList = []
				for(let i=0; i<dataList.length; i++) {
					let item = dataList[i]
					let condition = [
						{ key: "attachment_id", value: item.attachFile },
						{ key: "upload_state", value: "0" }
					]
					let res = await sqliteUtil.selectTableInfoMore('m_cpis_file_attachment', condition)
					fileList = fileList.concat(res)
				}
				return fileList
			},
			// 上传处理
			async handleUpload(type, fileList, dataList) {
				try {
					// 上传附件
					for(let i=0; i<fileList.length; i++) {
						let item = fileList[i]
						utilities.formatHumpLineTransfer(item)
						if(item.attachmentId && item.attachmentId != 'null') {
							let formData = {
								collectionId: item.attachmentId,
								businessCode: type == 'defect' ? 'oh' : 'insp',
								subBusinessCode: type == 'defect' ? 'df' : 'task',
								businessDataCode: type == 'defect' ? this.$t('defect.common.def') : type == 'task' ? this.$t('inspection.taskPlan.finishReport') : this.$t('inspection.taskPlan.taskPlan'),
								fileSum: 1,
								userName: uni.getStorageSync("userName"),
								fileUserName: uni.getStorageSync("userName")
							}
							
							file.uploadFileset(item.filePath, formData).then(res => {
								// 更新附件表
								let info = [
									{
										key: "upload_state",
										value: "10"
									}
								]
								let condi = [
									{
										key: "id",
										value: item.id
									}
								]
								sqliteUtil.modifyTableInfo('m_cpis_file_attachment', info, condi)
							})
						}
					}
					
					// 上传缺陷
					if(type == 'defect') {
						for(let i=0; i<dataList.length; i++) {
							let item = dataList[i]
							
							let info = await sqliteUtil.selectTableInfo('m_df_information', 'df_id', item.dfId)
							if(info) {
								utilities.formatHumpLineTransfer(info)
								uploadDefect(info[0])
							}
						}
					}
				}catch(e){
					return false
				}
				return true
			},
			async deleteOfflineTask() {
				// 删除巡检任务关联的附件
				let taskList = await sqliteUtil.selectTableInfo('m_ri_task', 'task_id', this.taskId)
				utilities.formatHumpLineTransfer(taskList)
				await this.deleteOfflineFile(taskList)
				
				// 删除 m_ri_task表数据
				await sqliteUtil.deleteTableInfo('m_ri_task', 'task_id', this.taskId)
				
				// 删除 m_ri_task_info表数据
				await sqliteUtil.deleteTableInfo('m_ri_task_info', 'task_id', this.taskId)
				
				// 查询检查项关联的缺陷
				let defectList = []
				let inspectList = await sqliteUtil.selectTableInfo('m_ri_task_inspection', 'task_id', this.taskId)
				utilities.formatHumpLineTransfer(inspectList)
				for(let i=0; i<inspectList.length; i++) {
					let item = inspectList[i]
					if(item.dfNo) {
						await sqliteUtil.selectTableInfo('m_df_information', 'df_id', item.dfNo).then(res=>{
							utilities.formatHumpLineTransfer(res)
							defectList.push(res[0])
						})
					}
				}
				
				// 删除巡检项关联的附件
				await this.deleteOfflineFile(inspectList)
				
				// 删除 m_ri_task_inspection表数据
				await sqliteUtil.deleteTableInfo('m_ri_task_inspection', 'task_id', this.taskId)
				
				// 删除缺陷关联的附件
				await this.deleteOfflineFile(defectList)
				
				// 删除 m_df_information表数据
				defectList.forEach(item => {
					sqliteUtil.deleteTableInfo('m_df_information', 'df_id', item.dfId)
				})
				
				// 删除 m_cpis_app_collect_status表数据
				await sqliteUtil.deleteTableInfo('m_cpis_app_collect_status')
			},
			async deleteOfflineFile(dataList) {
				for(let i=0; i<dataList.length; i++) {
					let item = dataList[i]
					if(item.attachFile && item.attachFile != "[]") {
						let files = item.attachFile.split(',')
						for(let j=0; j<files.length; j++) {
							sqliteUtil.deleteTableInfo('m_cpis_file_attachment', 'id', files[j])
						}
					}
				}
			}
		}
	}
</script>

<style>
</style>